package com.jack.xiaoer.web.controller;

import com.jack.xiaoer.constant.OrderStateEnum;
import com.jack.xiaoer.entity.Order;
import com.jack.xiaoer.service.OrderService;
import com.jack.xiaoer.util.AjaxResponse;
import com.jack.xiaoer.validator.Groups;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/22.
 */
@Validated
@RestController
@RequestMapping("/shop_serve")
public class ShopServeController extends BaseController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/order/list/{shopId}/{stateCode}")
    public AjaxResponse listForShopServe(@PathVariable Long shopId, @PathVariable Integer stateCode) {
        if (!OrderStateEnum.valid(stateCode)) {
            return AjaxResponse.invalid("订单状态参数错误");
        }

        List<Order> orders = orderService.listByShopIdAndState(shopId, stateCode);

        return AjaxResponse.success("获取订单列表成功", orders);
    }

    @PostMapping("/order/update")
    public AjaxResponse updateOrderState(@RequestBody @Validated({Groups.OrderUpdate.class}) Optional<Order> orderOptional, BindingResult bindingResult) {
        AjaxResponse error = commonValidate(orderOptional, bindingResult);
        if (error != null) {
            return error;
        }
        Integer orderState = orderOptional.get().getState();
        if ( orderState != null) {
            if (!OrderStateEnum.valid(orderState)) {
                return AjaxResponse.invalid("订单状态参数错误");
            }
        }

        Order updatedOrder = orderService.update(orderOptional);

        if (updatedOrder == null) {
            AjaxResponse.fail("订单状态更新失败");
        }

        return AjaxResponse.success("订单状态更新成功", updatedOrder);
    }


}
